#include "tcp_thread.h"
#include <QDebug>


tcp_thread::tcp_thread(QHostAddress ip,QString port, QObject *parent)
    : QThread(parent)
{
    TCPthread_start_flag = true;
    TCPthread_connect_flag = false;
    TCPthread_send_flag = false;
    TCPthread_receive_flag = false;

    tcp_server = new QTcpServer;
    tcp_socket = nullptr;

    if(tcp_server->listen(ip,port.toInt()))
    {
        connect(tcp_server, &QTcpServer::newConnection, this, &tcp_thread::ConnectNewClient);
        qDebug() << "IP和端口号绑定成功";
    }
    else
    {
        qDebug() << "IP和端口号绑定错误";
    }

    data_buffer_QS.clear();
}

void tcp_thread::ConnectNewClient()
{
    if(tcp_server->hasPendingConnections())
    {
        tcp_socket = tcp_server->nextPendingConnection();
        if(tcp_socket != nullptr)
        {
            client_ip = tcp_socket->peerAddress();
            client_port = tcp_socket->peerPort();
            TCPthread_connect_flag = true;
            qDebug() << "有新的客户端连接 ip号为 " << client_ip.toString() << " 端口号为 " << client_port;
            TCPthread_start_flag = true;
            TCPthread_send_flag = true;
            TCPthread_receive_flag = true;
        }
        //接收
        connect(tcp_socket, &QTcpSocket::readyRead, this , &tcp_thread::RecvClientMessage);
        //断开
        connect(tcp_socket, &QTcpSocket::disconnected, this , &tcp_thread::DisConnectNewClient);
    }
}

void tcp_thread::DisConnectNewClient()
{
    TCPthread_connect_flag = false;
    emit AbortTcpConnect();
}

void tcp_thread::run()
{
    while(TCPthread_start_flag)
    {
        tcp_thread::mutex_Stop();

        if(TCPthread_connect_flag)
        {
            if(TCPthread_send_flag)
            {
                // TCP发送string数据发出
                SendServerMessage();
            }
            if(TCPthread_receive_flag)
            {
                // TCP接受string数据 to struct结构体
                ParseTcpReceivedData(data_buffer_QS, Pendant_Techn_Param_ptr);
            }
        }

        tcp_thread::mutex_GoOn();
    }
}

void tcp_thread::mutex_Stop()
{
    mutex.lock();
}

void tcp_thread::mutex_GoOn()
{
    mutex.unlock();
}

tcp_thread::~tcp_thread()
{

}

/************************** 通信发送 **********************************/
void tcp_thread::SendServerMessage()
{
    while(!TCP_SendMsg_queue.isEmpty())
    {
        if(TCPthread_send_flag)
        {
            QString sendData_QS = TCP_SendMsg_queue.dequeue();
            QByteArray sendData_QBA = sendData_QS.toUtf8();
            tcp_socket->write(sendData_QBA);
            tcp_socket->waitForBytesWritten();
        }
    }
}
/************************** 通信发送 **********************************/

/************************** 通信接收 **********************************/
void tcp_thread::RecvClientMessage()
{
    if(TCPthread_connect_flag && TCPthread_start_flag && TCPthread_receive_flag)
    {
        QByteArray data_buffer_QBA;
        data_buffer_QBA = tcp_socket->readAll();
        data_buffer_QS = QString(data_buffer_QBA);
    }
    else
    {
        QByteArray data_buffer_QBA;
        data_buffer_QBA = tcp_socket->readAll();
        data_buffer_QBA.clear();
    }
    qDebug() << "待接收的原数据是" << data_buffer_QS;
}

void tcp_thread::removeFirstElement(QString &data)
{
    tinyxml2::XMLDocument XMLDoc;
    XMLDoc.Parse(data.toStdString().c_str());
    XMLElement *ele = XMLDoc.FirstChildElement();
    if(ele)
    {
        XMLDoc.DeleteNode(ele);
    }
    XMLPrinter printer;
    XMLDoc.Print(&printer);
    data = printer.CStr();
}

void tcp_thread::ParseTcpReceivedData(QString &data, Techn_Param_ptr tech_param)
{
    if(TCPthread_connect_flag)
    {
        if(TCPthread_receive_flag)
        {
            //处理输入数据流
            tinyxml2::XMLDocument XMLDoc;
            XMLDoc.Parse(data.toStdString().c_str());
            const XMLElement *ele = XMLDoc.FirstChildElement();
            while(ele)
            {
                if(isIoParam(ele))
                {
                    const XMLAttribute *ele_attribute = ele->FirstAttribute();
                    while(ele_attribute)
                    {
                        qDebug() << "被接收的原数据被解析,元素1 2 3分别是" << ele->Name() << ele_attribute->Name() << ele_attribute->Value();
                        setIoParam(ele, ele_attribute, tech_param);
                        ele_attribute = ele_attribute->Next();
                    }
                    removeFirstElement(data);
                }
                if(isAlarmParam(ele))
                {
                    const XMLAttribute *ele_attribute = ele->FirstAttribute();
                    while(ele_attribute)
                    {
                        qDebug() << "被接收的原数据被解析,元素1 2 3分别是" << ele->Name() << ele_attribute->Name() << ele_attribute->Value();
                        setAlarmParam(ele, ele_attribute, tech_param);
                        ele_attribute = ele_attribute->Next();
                    }
                    removeFirstElement(data);
                }
                ele = ele->NextSiblingElement();
            }
        }
    }
    return;
}

bool tcp_thread::isIoParam(const XMLElement *elementptr)
{
    const char *ele_name = elementptr->Name();
    //qDebug() << ele_name;

    //字符串相等时strcmp返回0
    bool isIoParam_1 = !strcmp(ele_name, "X04");
    bool isIoParam_2 = !strcmp(ele_name, "Y01");
    if(isIoParam_1 | isIoParam_2)
    {
        return true;
    }
    return false;
}

bool tcp_thread::isAlarmParam(const XMLElement *elementptr)
{
    const char *ele_name = elementptr->Name();
    //qDebug() << ele_name;

    //字符串相等时strcmp返回0
    bool isIoParam_1 = !strcmp(ele_name, "OperateErrorAlarm");
    bool isIoParam_2 = !strcmp(ele_name, "AxisAlarm");
    if(isIoParam_1 | isIoParam_2)
    {
        return true;
    }
    return false;
}
/************************** 通信接收 **********************************/
